count = 0


def merge_sort(lists):
    global count
    if len(lists) <= 1:
        return lists
    middle = len(lists)//2
    left = merge_sort(lists[:middle])
    right = merge_sort(lists[middle:])
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            # 因为两个队列都是有序的，所以如果出现左边大的情形，则左边后面的元素全都是逆序对
            count += len(left) - i
            result.append(right[j])
            j += 1

    if i == len(left):
        result += right[j:]
    else:
        result += left[i:]

    return result


a = [2, 6, 3, 4, 5, 1]
print(merge_sort(a))
print("count = ", count)
